#!/bin/sh
###############################################################################
##  Author    : xuezhoyi
##  Name      : edw_hivql_executor.sh
##  Functions : hql执行器
##  Purpose   : 
##  Revisions or Comments
##  VER        DATE        AUTHOR           DESCRIPTION
##---------  ----------  ---------------  ------------------------------------ 
##  1.0      2017-05-22  xuezhouyi        1. CREATED THIS SHELL.
##  2.0      2018-11-11  薛周毅           1.hql执行器
##                                        2.删除动态参数配置，默认使用平台所有参数
##                                        3.显示mr执行百分比
###############################################################################

. ${0%`basename ${0}`}edw_parm.sh
. ${0%`basename ${0}`}edw_func.sh

function USAGE(){
    LOGGER "ERROR" "How to use this shell script!"
    LOGGER "ERROR" "${V_SHELL_HOME}/edw_hivql_executor.sh -q \"select current_date;\""
    LOGGER "ERROR" "${V_SHELL_HOME}/edw_hivql_executor.sh -f \"/home/hadoop/dev/a.HQL\""
}

# Run SQL statement
function RUNSQL(){
    hive -S -e "${1};"
    SQLCODE=$?
    if [[ ${SQLCODE} -ne 0 ]]; then
      LOGGER "ERROR ${SQLCODE}" "SQL执行失败！"
      LOGGER "DEBUG" "SQL=${1}"
      exit ${SQLCODE}
    fi
}

# Run a SQL file
function RUNFILE(){
    hive -e "source ${1};"
    SQLCODE=$?
    if [[ ${SQLCODE} -ne 0 ]]; then
      LOGGER "ERROR ${SQLCODE}" "SQL执行失败！"
      LOGGER "DEBUG" "SQL=${1}"
      exit ${SQLCODE}
    fi
}

# export data
function EXPDATA(){
    hive -S -e "${1}"
    SQLCODE=$?
    if [[ ${SQLCODE} -ne 0 ]]; then
      LOGGER "ERROR ${SQLCODE}" "SQL执行失败！"
      LOGGER "DEBUG" "SQL=${1}"
      exit ${SQLCODE}
    fi
}

# get the parameter
while getopts :q:x:f: args;do
    case ${args} in
        q)
            V_HIVE_QUERY=${OPTARG}
        ;;
        x)
            V_EXP_DATA=${OPTARG}
        ;;
        f)
            V_HIVE_FILE=${OPTARG}
        ;;
        ?)
            USAGE
        ;;
    esac
done

# switch case
if [[ -f "${V_HIVE_FILE}" ]];then
    RUNFILE "${V_HIVE_FILE}"
elif [[ -n "${V_HIVE_QUERY}" ]];then
    RUNSQL "${V_HIVE_QUERY}"
elif [[ -n "${V_EXP_DATA}" ]];then
    EXPDATA "${V_EXP_DATA}"
else
    USAGE
fi
